#ifndef LOGGER_HPP
#define LOGGER_HPP

#include <chrono>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <mutex>
#include <sstream>
#include <string>

// 这里创建一个简单的日志系统
namespace tools {

// Logger类声明
class Logger {
public:
  // 日志类型枚举
  enum class LogType {
    INFO,
    WARNING,
    ERROR,
    USER_LOGIN,
    USER_REGISTER,
    
    USER_CHAT,
    USER_BANNED,
    ADMIN_ACTION
  };

  // 获取Logger单例
  static Logger &getInstance() {
    static Logger instance;
    return instance;
  }

  // 写入日志
  void log(LogType type, const std::string &userId,
           const std::string &message) {
    std::lock_guard<std::mutex> lock(mutex_); // 线程安全

    try {
      std::ofstream logFile(
          "/home/ccy/code_workspace/cpp_finall/resource/system_log.txt",
          std::ios::app); // 追加模式

      if (logFile.is_open()) {
        // 获取当前时间
        auto now = std::chrono::system_clock::now();
        auto time = std::chrono::system_clock::to_time_t(now);

        std::stringstream ss;
        ss << std::put_time(std::localtime(&time), "%Y-%m-%d %H:%M:%S");

        // 写入日志格式：[时间] [类型] [用户ID] 消息
        logFile << "[" << ss.str() << "] [" << logTypeToString(type) << "] ["
                << userId << "] " << message << std::endl;

        logFile.close();
      } else {
        std::cerr << "无法打开日志文件" << std::endl;
      }
    } catch (const std::exception &e) {
      std::cerr << "日志记录错误: " << e.what() << std::endl;
    }
  }

private:
  // 私有构造函数，确保单例
  Logger() {}

  // 防止拷贝和赋值
  Logger(const Logger &) = delete;
  Logger &operator=(const Logger &) = delete;

  std::mutex mutex_; // 互斥锁，确保线程安全

  // 将日志类型转换为字符串
  std::string logTypeToString(LogType type) {
    switch (type) {
    case LogType::INFO:
      return "INFO";
    case LogType::WARNING:
      return "WARNING";
    case LogType::ERROR:
      return "ERROR";
    case LogType::USER_LOGIN:
      return "LOGIN";
    case LogType::USER_REGISTER:
      return "REGISTER";
    case LogType::USER_CHAT:
      return "CHAT";
    case LogType::USER_BANNED:
      return "BANNED";
    case LogType::ADMIN_ACTION:
      return "ADMIN";
    default:
      return "UNKNOWN";
    }
  }
};

} // namespace tools

#endif // LOGGER_HPP
